<template>
  <div class="avue-contail"
       :class="{'avue--collapse':isCollapse}">
    <im></im>
    <div class="avue-header">
      <!-- 顶部导航栏 -->
     <top />
    </div>

    <div class="avue-layout">
      <div class="avue-left">
        <!-- 左侧导航栏 -->
        <sidebar />
      </div>
     <div class="avue-main">
        <!-- 顶部标签卡 -->
        <tags />
        <transition name="fade-scale">
          <search class="avue-view"
                  v-show="isSearch"></search>
        </transition>
        <!-- 主体视图层 -->
        <div style="height:100%;overflow:auto;"
             id="avue-view"
             v-if="!isRefresh"
             v-show="!isSearch">
          <keep-alive>
            <router-view class="avue-view"
                         v-if="$route.meta.$keepAlive" />
          </keep-alive>
          <router-view class="avue-view"
                       v-if="!$route.meta.$keepAlive" />
        </div>
      </div>
    </div>
    <!-- <el-footer class="avue-footer">
      <img src="/svg/logo.svg"
           alt=""
           class="logo">
      <p class="copyright">© 2018 Avue designed by smallwei</p>
    </el-footer> -->
    <div class="avue-shade"
         @click="showCollapse"></div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import tags from './tags';
import search from './search';
import im from './im';
import top from './top/';
import sidebar from './sidebar/';
import admin from '@/util/admin';
import { validatenull } from '@/util/validate';
import { calcDate } from '@/util/date.js';
import { getStore, setStore } from '@/util/store.js';
// import GLOBAL from '@/const/global_variable'
// import SockJS from  'sockjs-client';
// import Stomp from 'stompjs';
export default {
  components: {
    top,
    tags,
    search,
    sidebar,
    im
  },
  name: 'index',
  data () {
    return {
      //搜索控制
      isSearch: false,
      //刷新token锁
      refreshLock: false,
      //刷新token的时间
      refreshTime: "",
      stompClient: '',
      timer: ''
    };
  },
  created () {
    //实时检测刷新token
    // this.refreshToken();
  },
  mounted () {
    this.init();
    // this.initWebSocket();
    if ('WebSocket' in window) {
      // this.websocket = new WebSocket('ws://' + location.host + '/websocketapi')      
      this.websocket = new WebSocket('ws://' + this.$store.getters.userInfo.websoketURL)
      // this.websocket = new WebSocket(GLOBAL.websoketUrl)
      this.initWebSocket()
    } else {
      alert('当前浏览器 Not support websocket')
    }
  },
  beforeDestroy () {
    this.onbeforeunload()
    // 页面离开时断开连接,清除定时器
    // this.disconnect();
    // clearInterval(this.timer);
  },
  computed: mapGetters(['isLock', 'isCollapse', 'website', 'isRefresh']),
  props: [],
  methods: {
    showCollapse () {
      this.$store.commit('SET_COLLAPSE');
    },
    // 屏幕检测
    init () {
      this.$store.commit('SET_SCREEN', admin.getScreen());
      window.onresize = () => {
        setTimeout(() => {
          this.$store.commit('SET_SCREEN', admin.getScreen());
        }, 0);
      };
    },
    // 10分钟检测一次token
    refreshToken () {
      this.refreshTime = setInterval(() => {
        const token = getStore({
          name: "token",
          debug: true
        });
        const date = calcDate(token.datetime, new Date().getTime());
        if (validatenull(date)) return;
        if (date.seconds >= this.website.tokenTime && !this.refreshLock) {
          this.refreshLock = true;
          // this.$store
          //   .dispatch("RefeshToken")
          //   .then(() => {
          //     this.refreshLock = false;
          //   })
          //   .catch(() => {
          //     this.refreshLock = false;
          //   });
        }
      }, 1000);
    },
    initWebSocket () {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage

      // 连接成功
      this.websocket.onopen = this.setOnopenMessage

      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage

      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage () {
      console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
    },
    setOnopenMessage () {
      let actions = {
        uid: this.$store.getters.userInfo.id,
        type: 'init',
        message: ''
      };     //请根据实际项目需要进行修改
      this.websocketsend(JSON.stringify(actions));
      console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)
      window.setInterval(() => {
        window.setTimeout(this.reinit(), 0)
      }, 1000 * 60 * 10)
    },
    reinit(){
      let actions = {
        uid: this.$store.getters.userInfo.id,
        type: 'init',
        message: ''
      };     //请根据实际项目需要进行修改
      this.websocketsend(JSON.stringify(actions));
      console.log('WebSocket心跳包发送成功    状态码：' + this.websocket.readyState)
    },
    websocketsend(Data){ // 数据发送
      this.websocket.send(Data);
    },
    setOnmessageMessage () {
      if (event.data && event.data != '') {
        this.redata = JSON.parse(event.data);
        console.log('服务端返回：',this.redata);
        // 根据服务器推送的消息做自己的业务处理
        console.log(event)
        console.log('服务端返回：' + event.data)
        this.$set(this.$store.state, 'msgsLen', parseInt(this.$store.state.msgsLen) + 1)
        setStore({ name: 'msgsLen', content: parseInt(this.$store.state.msgsLen) + 1, type: 'session' })
        this.$store.commit("SET_OBJ", { key: 'msgsLen', obj: parseInt(this.$store.state.msgsLen) + 1 })
        this.$notify.info({
          title: '消息提示',
          message: this.redata.message,
          position: 'bottom-right',
          duration: 0
        });
      }     
    },
    setOncloseMessage () {
      console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
    },
    onbeforeunload () {
      this.closeWebSocket()
    },
    closeWebSocket () {
      this.websocket.close()
    }
    // initWebSocket() {
    //   this.connection();
    //   let that= this;
    //   // 断开重连机制,尝试发送消息,捕获异常发生时重连
    //   this.timer = setInterval(() => {
    //     try {
    //       that.stompClient.send("test");
    //     } catch (err) {
    //       console.log("断线了: " + err);
    //       that.connection();
    //     }
    //   }, 5000);
    // },  
    // connection() {
    //   // 建立连接对象
    //   let socket = new SockJS('http://' + location.host + '/websocketapi');
    //   // 获取STOMP子协议的客户端对象
    //   this.stompClient = Stomp.over(socket);
    //   // 定义客户端的认证信息,按需求配置
    //   let headers = {
    //     uid: this.$store.getters.userInfo.id,
    //     token: this.$store.getters.token
    //   }
    //   // 向服务器发起websocket连接
    //   this.stompClient.connect(headers,() => {
    //     // this.stompClient.subscribe('/topic/public', (msg) => { // 订阅服务端提供的某个topic
    //     //     console.log('广播成功')
    //     //     console.log(msg);  // msg.body存放的是服务端发送给我们的信息
    //     // },headers);
    //     // this.stompClient.send("/app/chat.addUser",
    //     //     headers,
    //     //     JSON.stringify({sender: '',chatType: 'JOIN'}),
    //     // )   //用户加入接口
    //   }, (err) => {
    //     // 连接发生错误时的处理函数
    //     console.log('失败')
    //     console.log(err);
    //   });
    // },    //连接 后台
    // disconnect() {
    //   if (this.stompClient) {
    //     this.stompClient.disconnect();
    //   }
    // }  // 断开连接
  }
};
</script>